"""
API场景组合测试工具 - 脚本引擎
"""
import json
import re
from datetime import datetime

class ScriptEngine:
    """脚本执行引擎，支持变量替换、条件判断和循环操作"""
    
    def __init__(self):
        """初始化"""
        self.global_functions = {
            'json_path': self._json_path,
            'json_parse': self._json_parse,
            'json_stringify': self._json_stringify,
            'current_time': self._current_time,
            'format_date': self._format_date,
            'random_string': self._random_string,
            'random_number': self._random_number,
            'log': self._log,
        }
    
    def execute_script(self, script, context):
        """执行脚本"""
        # 创建一个安全的执行环境
        exec_globals = {
            'context': context,
            'result': {},
            'variables': {},
            **self.global_functions
        }
        
        # 执行脚本
        try:
            exec(script, exec_globals)
            
            # 返回结果和变量
            return {
                'result': exec_globals.get('result', {}),
                'variables': exec_globals.get('variables', {})
            }
        except Exception as e:
            raise Exception(f"脚本执行错误: {str(e)}")
    
    def _json_path(self, obj, path):
        """从JSON对象中获取指定路径的值"""
        if not obj or not path:
            return None
        
        parts = path.split('.')
        current = obj
        
        for part in parts:
            # 处理数组索引，如 items[0]
            array_match = re.match(r'(.+)\[(\d+)\]', part)
            if array_match:
                array_name = array_match.group(1)
                array_index = int(array_match.group(2))
                
                if array_name in current and isinstance(current[array_name], list) and len(current[array_name]) > array_index:
                    current = current[array_name][array_index]
                else:
                    return None
            else:
                if isinstance(current, dict) and part in current:
                    current = current[part]
                else:
                    return None
        
        return current
    
    def _json_parse(self, json_str):
        """解析JSON字符串为对象"""
        try:
            return json.loads(json_str)
        except:
            return None
    
    def _json_stringify(self, obj):
        """将对象转换为JSON字符串"""
        try:
            return json.dumps(obj, ensure_ascii=False)
        except:
            return '{}'
    
    def _current_time(self, format_str='%Y-%m-%d %H:%M:%S'):
        """获取当前时间"""
        return datetime.now().strftime(format_str)
    
    def _format_date(self, date_str, input_format='%Y-%m-%d %H:%M:%S', output_format='%Y-%m-%d %H:%M:%S'):
        """格式化日期"""
        try:
            dt = datetime.strptime(date_str, input_format)
            return dt.strftime(output_format)
        except:
            return date_str
    
    def _random_string(self, length=8):
        """生成随机字符串"""
        import random
        import string
        return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
    
    def _random_number(self, min_val=0, max_val=100):
        """生成随机数字"""
        import random
        return random.randint(min_val, max_val)
    
    def _log(self, message):
        """记录日志"""
        print(f"[Script Log] {message}")
        return message